package com.common.base.service.impl;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.math.BigDecimal;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import jxl.Workbook;
import jxl.format.UnderlineStyle;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

import org.apache.commons.lang.StringUtils;

import com.common.base.dao.BaseDao;
import com.common.base.entity.BaseEntity;
import com.common.base.exceptions.DaoException;
import com.common.base.service.BaseService;
import com.common.base.util.ServiceHelper;
import com.common.tag.Page;

public class BaseServiceImpl<T extends BaseEntity> implements BaseService<T> {

	private BaseDao<T> baseDao;

	protected Class<T> entityClass; // model's Class
	protected String entityClassName; // model's ClassName

	@SuppressWarnings("unchecked")
	public BaseServiceImpl() {

		Object superClassType = getClass().getGenericSuperclass();

		if (superClassType instanceof ParameterizedType) {
			entityClass = (Class<T>) ((ParameterizedType) getClass()
					.getGenericSuperclass()).getActualTypeArguments()[0];
			entityClassName = entityClass.getSimpleName();
		}
	}

	@SuppressWarnings("unchecked")
	public BaseDao<T> getBaseDao() {
		BaseDao<T> baseDao = null;
		if (this.entityClass != null) {
			baseDao = (BaseDao<T>) ServiceHelper.findBean(StringUtils
					.uncapitalize(entityClassName)
					+ "Dao");
		} else {
			baseDao = this.baseDao;
		}
		return baseDao;
	}

	public void setBaseDao(BaseDao<T> baseDao) {
		this.baseDao = baseDao;
	}

	// 通用方法

	public BigDecimal insert(T entity) throws DaoException {
		return this.getBaseDao().insert(entity);
	}

	public int delete(T entity) {
		return this.getBaseDao().delete(entity);
	}

	public final int update(T entity) {
		return this.getBaseDao().update(entity);
	}

	public final List<T> findByParams(Map<String, Object> params) {
		if(params==null){
			params=new HashMap<String, Object>();
		}
		return this.getBaseDao().findByParams(params);
	}
	
	public T findBySid(Long sid){
		return this.getBaseDao().findBySid(sid);
	}
	
	/**
	 * 分页查询
	 * @pageCur 当前页码
	 * @pageSize 每页显示的记录条数
	 * */
	public Page<T> findByPage(Map<String, Object> params, int pageCur, int pageSize){
		
		return this.getBaseDao().findByPage(params, pageCur, pageSize);
	}

	/** ***************************以下是导出excel的新功能的实现****完善中********************************************* */

	// 读取properties的全部信息
	@SuppressWarnings("unchecked")
	public Map<String, String> getProperties(String path) {
		Map<String, String> resultMap = new HashMap<String, String>();
		Properties props = new Properties();
		try {
			InputStream in = new BufferedInputStream(new FileInputStream(path));
			// InputStream in =
			// this.getClass().getClassLoader().getResourceAsStream(filePath);
			props.load(in);
			Enumeration en = props.propertyNames();
			while (en.hasMoreElements()) {
				String key = (String) en.nextElement();
				String Property = props.getProperty(key);
				resultMap.put(key, Property);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return resultMap;
	}

	public String getExcel(List<T> list, String excelTitle, String excelName) throws Exception {

		String excelValueStr = excelTitle;
			// this.getProperties().get(excelTitle);
		String[] mo = excelValueStr.split(",");
		String[] keys = new String[mo.length];
		String[] values = new String[mo.length];

		String excelPath = System.getProperty("user.dir") + "/" + excelName + ".xls";

		WritableWorkbook book = Workbook.createWorkbook(new File(excelPath)); // 第一步创建Excel文件

		WritableSheet sheet = book.createSheet("sheet1", 0); // 创建Sheet
		// sheet.setColumnView(0, 30); // 设置列的宽度
		// sheet.setColumnView(1, 30); // 设置列的宽度
		// sheet.setColumnView(2, 30); // 设置列的宽度
		// sheet.setRowView(6, 1000); // 设置行的高度
		// sheet.setRowView(4, 1000); // 设置行的高度
		// sheet.setRowView(5, 1000); // 设置行的高度

		/**
		 * 定义单元格样式
		 */
		WritableFont wf = new WritableFont(WritableFont.ARIAL, 15,
				WritableFont.BOLD, false, UnderlineStyle.NO_UNDERLINE,
				jxl.format.Colour.CORAL); // 定义格式 字体 下划线 斜体 粗体 颜色
		WritableCellFormat wcf = new WritableCellFormat(wf); // 单元格定义

		wcf.setBackground(jxl.format.Colour.BLUE); // 设置单元格的背景颜色
		wcf.setAlignment(jxl.format.Alignment.CENTRE); // 设置对齐方式

		sheet.mergeCells(0, 0, values.length - 1, 0);
		sheet.addCell(new Label(0, 0, excelName, wcf)); // 合并单元格

		for (int i = 0; i < mo.length; i++) {
			String[] mt = mo[i].split(":");
			keys[i] = "get" + mt[0].substring(0, 1).toUpperCase()
					+ mt[0].substring(1);
			values[i] = mt[1];
			sheet.addCell(new Label(i, 1, mt[1]));
		}
		int i = 2;
		for (T entity : list) {

			for (int j = 0; j < keys.length; j++) {
				Method getMethod = entityClass.getMethod(keys[j],new Class[] {});
				Object value = getMethod.invoke(entity, new Object[] {});
				String results = "";
				if (value != null) {
					results = String.valueOf(value);
				}
				sheet.addCell(new Label(j, i, results));
			}
			i++;
		}
		book.write();
		book.close();

		return excelPath;
	}
}
